package com.dqhl.business.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.business.Base.BaseActivity;
import com.dqhl.business.R;
import com.dqhl.business.modle.GoodsClass;
import com.dqhl.business.modle.GoodsDetail;
import com.dqhl.business.util.Config;
import com.dqhl.business.util.Constant;
import com.dqhl.business.util.Dlog;
import com.dqhl.business.util.JsonUtils;
import com.dqhl.business.view.GoodsClassPopupWindow;
import com.dqhl.business.view.PictureHandlePopupWindow;
import com.dqhl.business.view.PictureSelectPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * description: 商品详情
 * autour: guanluocang
 * date: 2016/11/6 10:09
 */
public class AddGoodsActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    private TextView tv_goodsTopTitle;
    private ImageView iv_goodsGoBack;
    private ImageView iv_addPicOne;
    private ImageView iv_addPicTwo;
    private ImageView iv_addPicThree;
    private ImageView iv_addPicFour;
    private ImageView iv_addPic;
    private EditText et_goodsName;
    private EditText et_goodsUnit;
    private EditText et_goodsPrice;
    private EditText et_goodsSpec;
    private EditText et_goodsNum;
    private EditText et_content;
    //添加图片
    private static int REQUESTCODE_PICTURE = 100;
    private static int REQUESTCODE_CAMERA = 101;
    private PictureSelectPopupWindow pictureSelectPopupWindow;
    private PictureHandlePopupWindow pictureHandlePopupWindow;
    private String namePicOne = "", namePicTwo = "", namePicThree = "", namePicFour = "";
    private int countPic = 0;// 添加图片数量  imageview处图片是否为空
    private int TAG = 0;//  标记是那张图片

    private TextView tv_save;
    private TextView tv_release;
    private TextView tv_goodsType;
    private GoodsClassPopupWindow goodsClassPopupWindow;
    private String goodsId;
    //    private GoodsDetail goodsDetail;
    private List<GoodsClass> goodsClassList;
    private List<String> picList;
    private String classId;
    private String classSon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_add);
        context = this;
        initView();
    }

    private void initView() {
        (tv_goodsTopTitle) = (TextView) findViewById(R.id.tv_goodsTopTitle);
        tv_goodsTopTitle.setText("添加商品");
        (iv_goodsGoBack) = (ImageView) findViewById(R.id.iv_goodsGoBack);
        (iv_addPicOne) = (ImageView) findViewById(R.id.iv_addPictureOne);
        (iv_addPicTwo) = (ImageView) findViewById(R.id.iv_addPictureTwo);
        (iv_addPicThree) = (ImageView) findViewById(R.id.iv_addPictureThree);
        (iv_addPicFour) = (ImageView) findViewById(R.id.iv_addPictureFour);
        (iv_addPic) = (ImageView) findViewById(R.id.iv_addPicture);
        (tv_save) = (TextView) findViewById(R.id.tv_save);
        (tv_release) = (TextView) findViewById(R.id.tv_release);
        (tv_goodsType) = (TextView) findViewById(R.id.tv_goodsType);
        et_goodsName = (EditText) findViewById(R.id.et_goodsName);
        et_goodsUnit = (EditText) findViewById(R.id.et_goodsUnit);
        et_goodsPrice = (EditText) findViewById(R.id.et_goodsPrice);
        et_goodsSpec = (EditText) findViewById(R.id.et_goodsSpec);
        et_goodsNum = (EditText) findViewById(R.id.et_goodsNum);
        et_content = (EditText) findViewById(R.id.et_content);

        tv_goodsType.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        tv_release.setOnClickListener(this);
        iv_addPic.setOnClickListener(this);
        iv_addPicOne.setOnClickListener(this);
        iv_addPicTwo.setOnClickListener(this);
        iv_addPicThree.setOnClickListener(this);
        iv_addPicFour.setOnClickListener(this);
        iv_goodsGoBack.setOnClickListener(this);
        pictureSelectPopupWindow = new PictureSelectPopupWindow(this, pictureSelectItemsOnClick);
        pictureHandlePopupWindow = new PictureHandlePopupWindow(this, pictureHandleItemsOnClick);
        pictureSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureSelectPopupWindow.backgroundAlpha(1.0f);
            }
        });
        pictureHandlePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureHandlePopupWindow.backgroundAlpha(1.0f);
            }
        });
    }

    View.OnClickListener pictureSelectItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_take_photo:   // 调用系统相机
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(camera, REQUESTCODE_CAMERA);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_pick_photo:   // 调取手机相册
                    Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(picture, REQUESTCODE_PICTURE);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_cancel:   // 取消
                    pictureSelectPopupWindow.dismiss();
                    break;
            }
        }
    };


    View.OnClickListener pictureHandleItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_big_picture:
                    pictureHandlePopupWindow.dismiss();
                    Bundle bundle = new Bundle();
                    if (TAG == 1) {
                        bundle.putString("img_path", namePicOne);
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 2) {
                        bundle.putString("img_path", namePicTwo);
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 3) {
                        bundle.putString("img_path", namePicThree);
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 4) {
                        bundle.putString("img_path", namePicFour);
                        overlay(ImageShowerActivity.class, bundle);
                    }
                    break;
                case R.id.btn_delete: // 删除图片
                    pictureHandlePopupWindow.dismiss();
                    deleteImage();
                    break;
                case R.id.btn_cancel:
                    pictureHandlePopupWindow.dismiss();
                    break;
            }
        }
    };


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_goodsGoBack:
                finish();
                break;
            case R.id.iv_addPicture:
                if (countPic == 0) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_manager), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else if (countPic == 1) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_manager), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else if (countPic == 2) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_manager), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else if (countPic == 3) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_manager), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_addPictureOne:
                TAG = 1;
                pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_manager), Gravity.BOTTOM, 0, 0);
                pictureHandlePopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.iv_addPictureTwo:
                TAG = 2;
                pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_manager), Gravity.BOTTOM, 0, 0);
                pictureHandlePopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.iv_addPictureThree:
                TAG = 3;
                pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_manager), Gravity.BOTTOM, 0, 0);
                pictureHandlePopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.iv_addPictureFour:
                TAG = 4;
                pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_manager), Gravity.BOTTOM, 0, 0);
                pictureHandlePopupWindow.backgroundAlpha(0.5f);
                break;
            //保存
            case R.id.tv_save:
                doSave();
                break;
            //发布
            case R.id.tv_release:
                doSave();
                break;
            //商品分类
            case R.id.tv_goodsType:
                showTypePopWindow();
                break;
        }
    }

    /**
     * 保存
     */
    private void doSave() {
        String name = et_goodsName.getText().toString();
        String unit = et_goodsUnit.getText().toString();
        String price = et_goodsPrice.getText().toString();
        String stock = et_goodsNum.getText().toString();
        String info = et_content.getText().toString();
        String class_son = et_goodsSpec.getText().toString();
        File pic_a = new File(namePicOne);
        File pic_b = new File(namePicTwo);
        File pic_c = new File(namePicThree);
        File pic_d = new File(namePicFour);
        if (TextUtils.isEmpty(name)) {
            toast("请填写商品名称");
        } else if (TextUtils.isEmpty(unit)) {
            toast("请填写单位");
        } else if (TextUtils.isEmpty(price)) {
            toast("请填写单价");
        } else if (TextUtils.isEmpty(class_son)) {
            toast("请填写规格");
        } else if (TextUtils.isEmpty(stock)) {
            toast("请填写库存");
        } else if (TextUtils.isEmpty(info)) {
            toast("请填写商品描述");
        } else if (TextUtils.isEmpty(classId)) {
            toast("请填写商品分类");
        } else {
            Dlog.e(user.getUser_id() + ";" + name + ";" + unit + ";" + stock + ";" + info + ";" + price + ";" + class_son + ";" + classId);
            showCustomLoadBar(".");
            RequestParams params = new RequestParams(Config.management_goods_add);
            params.addBodyParameter("seller_id", user.getUser_id());
            params.addBodyParameter("name", name);
            params.addBodyParameter("unit", unit);
            params.addBodyParameter("price", price);
            params.addBodyParameter("stock", stock);
            params.addBodyParameter("info", info);
            if (!pic_a.isFile()) {
                pic_a = null;
            } else {
                Dlog.e("执行了picA");
                Dlog.e(pic_a + "");
                params.addBodyParameter("pic_a", pic_a);
            }
            if (!pic_b.isFile()) {
                pic_b = null;
            } else {
                Dlog.e("执行了picB");
                Dlog.e(pic_b + "");
                params.addBodyParameter("pic_b", pic_b);
            }
            if (!pic_c.isFile()) {
                pic_c = null;
            } else {
                Dlog.e("执行了picC");
                Dlog.e(pic_c + "");
                params.addBodyParameter("pic_c", pic_c);
            }
            if (!pic_d.isFile()) {
                pic_d = null;
            } else {
                Dlog.e("执行了picD");
                Dlog.e(pic_d + "");
                params.addBodyParameter("pic_d", pic_d);
            }
            params.addBodyParameter("class_son", class_son);
            params.addBodyParameter("class_id", classId);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (0 == errCode) {
                        sendAddSuccessBroadcast();
                        finish();
                    } else if (200 == errCode) {
                        toast("您未更改或修改失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Dlog.e(ex.getMessage());
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    Dlog.e(cex.getMessage());
                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

    private void sendAddSuccessBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_EDIT_GOODS);
        sendBroadcast(intent);
    }

    //商品分类popWindow
    private void showTypePopWindow() {
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.management_goods_type_list);
        params.addBodyParameter("seller_id", user.getUser_id());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                if (0 == errCode) {
                    goodsClassList = JSON.parseArray(data, GoodsClass.class);
                    goodsClassPopupWindow = new GoodsClassPopupWindow(context, goodsClassList,
                            new GoodsClassPopupWindow.IOnItemSelectListener() {
                                @Override
                                public void onItemClick(int position) {
                                    classId = goodsClassList.get(position).getId();
                                    tv_goodsType.setText(goodsClassList.get(position).getName());
                                }
                            });
                    goodsClassPopupWindow.setWidth(tv_goodsType.getWidth());
                    goodsClassPopupWindow.showAsDropDown(tv_goodsType);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == REQUESTCODE_PICTURE && resultCode == RESULT_OK) {
//                Uri selectedImage = data.getData();
                Uri selectedImage = geturi(data);
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                if (c != null) {
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    //添加图片
                    addImages(picturePath);
                }

            }
            if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK) {
                String sdState = Environment.getExternalStorageState();
                if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                    Dlog.e("sd card unmount");
                }
                String name = UUID.randomUUID().toString() + ".jpg";
                File file = new File("/sdcard/pintu");
                file.mkdirs();
                Bundle bundle = data.getExtras();
                //获取相机返回的数据，并转换为图片格式
                Bitmap bitmap = (Bitmap) bundle.get("data");
                FileOutputStream fout = null;
                String fileName = file.getPath() + name;
                try {
                    fout = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                    addImages(fileName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fout.flush();
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    /**
     * 解决小米部分手机调用系统相册失败
     *
     * @param intent
     * @return
     */

    public Uri geturi(Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }

    //添加图片
    public void addImages(String path) {
        if (countPic == 0) {
            if ("".equals(namePicOne) && namePicOne.length() == 0) {
                namePicOne = path;
//                picAisFromNet = false;
                iv_addPicOne.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicOne, namePicOne);
                countPic += 1;
            }
        } else if (countPic == 1) {
            if ("".equals(namePicOne) && namePicOne.length() == 0) {
                namePicOne = path;
//                picAisFromNet = false;
                iv_addPicOne.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicOne, namePicOne);
                countPic += 1;
            } else if ("".equals(namePicTwo) && namePicTwo.length() == 0) {
                namePicTwo = path;
//                picBisFromNet = false;
                iv_addPicTwo.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicTwo, namePicTwo);
                countPic += 1;
            } else if ("".equals(namePicThree) && namePicThree.length() == 0) {
                namePicThree = path;
//                picCisFromNet = false;
                iv_addPicThree.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicThree, namePicThree);
                iv_addPic.setVisibility(View.GONE);
                countPic += 1;
            } else if ("".equals(namePicFour) && namePicFour.length() == 0) {
                namePicFour = path;
//                picDisFromNet = false;
                iv_addPicFour.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicFour, namePicFour);
                countPic += 1;
                iv_addPic.setVisibility(View.GONE);
            }
        } else if (countPic == 2) {
            if ("".equals(namePicOne) && namePicOne.length() == 0) {
                namePicOne = path;
//                picAisFromNet = false;
                iv_addPicOne.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicOne, namePicOne);
                countPic += 1;
            } else if ("".equals(namePicTwo) && namePicTwo.length() == 0) {
                namePicTwo = path;
//                picBisFromNet = false;
                iv_addPicTwo.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicTwo, namePicTwo);
                countPic += 1;
            } else if ("".equals(namePicThree) && namePicThree.length() == 0) {
                namePicThree = path;
//                picCisFromNet = false;
                iv_addPicThree.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicThree, namePicThree);
                countPic += 1;
            } else if ("".equals(namePicFour) && namePicFour.length() == 0) {
                namePicFour = path;
//                picDisFromNet = false;
                iv_addPicFour.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicFour, namePicFour);
                iv_addPic.setVisibility(View.GONE);
                countPic += 1;
            }
        } else if (countPic == 3) {
            if ("".equals(namePicOne) && namePicOne.length() == 0) {
                namePicOne = path;
//                picAisFromNet = false;
                iv_addPicOne.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicOne, namePicOne);
                iv_addPic.setVisibility(View.GONE);
                countPic += 1;
            } else if ("".equals(namePicTwo) && namePicTwo.length() == 0) {
                namePicTwo = path;
//                picBisFromNet = false;
                iv_addPicTwo.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicTwo, namePicTwo);
                iv_addPic.setVisibility(View.GONE);
                countPic += 1;
            } else if ("".equals(namePicThree) && namePicThree.length() == 0) {
                namePicThree = path;
//                picCisFromNet = false;
                iv_addPicThree.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicThree, namePicThree);
                iv_addPic.setVisibility(View.GONE);
                countPic += 1;
            } else if ("".equals(namePicFour) && namePicFour.length() == 0) {
                namePicFour = path;
//                picDisFromNet = false;
                iv_addPicFour.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicFour, namePicFour);
                countPic += 1;
                iv_addPic.setVisibility(View.GONE);
            }
        }
    }

    //删除图片
    public void deleteImage() {
        if (TAG == 1) {
            namePicOne = "";
            iv_addPicOne.setVisibility(View.GONE);
            iv_addPic.setVisibility(View.VISIBLE);
            iv_addPic.setImageResource(R.drawable.ic_addpicture);
            countPic -= 1;
        } else if (TAG == 2) {
            namePicTwo = "";
            iv_addPicTwo.setVisibility(View.GONE);
            iv_addPic.setVisibility(View.VISIBLE);
            iv_addPic.setImageResource(R.drawable.ic_addpicture);
            countPic -= 1;
        } else if (TAG == 3) {
            namePicThree = "";
            iv_addPicThree.setVisibility(View.GONE);
            iv_addPic.setVisibility(View.VISIBLE);
            iv_addPic.setImageResource(R.drawable.ic_addpicture);
            countPic -= 1;
        } else if (TAG == 4) {
            namePicFour = "";
            iv_addPicFour.setVisibility(View.GONE);
            iv_addPic.setVisibility(View.VISIBLE);
            iv_addPic.setImageResource(R.drawable.ic_addpicture);
            countPic -= 1;
        }
    }

}
